package com.itheima.aspect;

import com.itheima.entity.Emp;
import com.itheima.entity.EmpLoginLog;
import com.itheima.entity.Result;
import com.itheima.mapper.EmpLoginLogMapper;
import com.itheima.mapper.OperateLogMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Aspect
public class EmpLoginLogAspect {
    @Autowired
    EmpLoginLogMapper empLoginLogMapper;


    // login操作，获取令牌，直接从请求头获取令牌：登录操作
    @Around("execution(com.itheima.entity.Result com.itheima.controller.loginController.login(com.itheima.entity.Emp))")
    public Object empLoginLog(ProceedingJoinPoint pjp) throws Throwable { //连接点：目标方法


        //1.执行目标
        long begin = System.currentTimeMillis();
        Object result = pjp.proceed(); //执行登录方法
        long end = System.currentTimeMillis();
        //获取目标方法的参数对象
        Object[] args = pjp.getArgs();
        Emp emp = (Emp) args[0];


        // 2.记录登录日志
        //2.1封装日志对象
        EmpLoginLog empLoginLog = new EmpLoginLog();
        empLoginLog.setLoginTime(LocalDateTime.now());

        empLoginLog.setUsername(emp.getUsername()); // 获取目标方法的参数对象emp
        empLoginLog.setPassword(emp.getPassword());

        empLoginLog.setCostTime(end - begin);

        Result resultLogin = (Result) result; //目标方法的执行结果
        empLoginLog.setIsSuccess(Short.parseShort(resultLogin.getCode()+"")); //获取目标方法的执行结果Result，获取登录结果
        empLoginLog.setJwt((String) resultLogin.getData()); // 获取目标方法的执行结果REsult，获取令牌结果


        // 调用持久层
        empLoginLogMapper.inser(empLoginLog);

        return result;
    }
}
